import { ILayout, IMenubarStatus, ITagsList, IMenubarList, ISetting, IToken } from '/@/type/store/layout'
import router, { GenerateRouter } from '/@/router/index'
import { allowRouter } from '/@/router/index'
import { generatorDynamicRouter } from '/@/router/asyncRouter'
import changeTheme from '/@/utils/changeTheme'
import { getLocal } from '/@/utils/index'
import { RouteLocationNormalizedLoaded } from 'vue-router'
import { store } from '/@/store/index'
import config from '../../config'  //用户配置的
import defaultConfig from '../../config/default'
import deepmerge from 'deepmerge'
const localSetting = getLocal<ISetting>('setting') //本地缓存的布局
const setting = deepmerge(config,localSetting)
const state: ILayout = {
    menubar: {
        status: document.body.offsetWidth < 768 ? IMenubarStatus.PHN : IMenubarStatus.PCE,
        menuList: [],
        isPhone: document.body.offsetWidth < 768
    },

    // 标签栏
    tags: {
        tagsList: [],
        cachedViews: []
    },
    palettes: defaultConfig.ADMIN.palettes,//画板 改主题颜色
    setting,
    isLoading: false  
}
const mutations = {
    changeCollapsed(state: ILayout): void {
        if (state.menubar.isPhone) {
            state.menubar.status = state.menubar.status === IMenubarStatus.PHN ? IMenubarStatus.PHE : IMenubarStatus.PHN
        } else {
            state.menubar.status = state.menubar.status === IMenubarStatus.PCN ? IMenubarStatus.PCE : IMenubarStatus.PCN
        }
    },
    changeDeviceWidth(state: ILayout): void {
        if (document.body.offsetWidth < 768) {
            state.menubar.isPhone = true
            state.menubar.status = IMenubarStatus.PHN
        } else {
            state.menubar.isPhone = false
            state.menubar.status = IMenubarStatus.PCE
        }
    },
    // 切换导航，记录打开的导航
    changeTagNavList(state: ILayout, cRouter: RouteLocationNormalizedLoaded): void {
        if (!state.setting.multiPage) return // 判断是否开启多标签页
        if (cRouter.meta.hidden && !cRouter.meta.activeMenu) return // 隐藏的菜单如果不是子菜单则不添加到标签
        const index = state.tags.tagsList.findIndex(v => v.path === cRouter.path)
        state.tags.tagsList.forEach(v => v.isActive = false)
        // 判断页面是否打开过
        if (index !== -1) {
            state.tags.tagsList[index].isActive = true
            return
        }
        const tagsList: ITagsList = {
            name: cRouter.name as string,
            title: cRouter.meta.title as string,
            path: cRouter.path,
            isActive: true
        }
        state.tags.tagsList.push(tagsList)
    },
    removeTagNav(state: ILayout, obj: { tagsList: ITagsList, cPath: string }): void {
        const index = state.tags.tagsList.findIndex(v => v.path === obj.tagsList.path)
        if (state.tags.tagsList[index].path === obj.cPath) {
            state.tags.tagsList.splice(index, 1)
            const i = index === state.tags.tagsList.length ? index - 1 : index
            state.tags.tagsList[i].isActive = true
            mutations.removeCachedViews(state, { name: obj.tagsList.name, index })
            router.push({ path: state.tags.tagsList[i].path })
        } else {
            state.tags.tagsList.splice(index, 1)
            mutations.removeCachedViews(state, { name: obj.tagsList.name, index })
        }
    },
    removeOtherTagNav(state: ILayout, tagsList: ITagsList): void {
        const index = state.tags.tagsList.findIndex(v => v.path === tagsList.path)
        state.tags.tagsList.splice(index + 1)
        state.tags.tagsList.splice(0, index)
        state.tags.cachedViews.splice(index + 1)
        state.tags.cachedViews.splice(0, index)
        router.push({ path: tagsList.path })
    },
    removeAllTagNav(state: ILayout): void {
        state.tags.tagsList.splice(0)
        state.tags.cachedViews.splice(0)
        router.push({ path: '/redirect/' })
    },
    // 添加缓存页面
    addCachedViews(state: ILayout, obj: { name: string, noCache: boolean }): void {
        if (!state.setting.multiPage) return // 判断是否开启多标签页
        if (obj.noCache || state.tags.cachedViews.includes(obj.name)) return
        state.tags.cachedViews.push(obj.name)
    },
    // 删除缓存页面
    removeCachedViews(state: ILayout, obj: { name: string, index: number }): void {
        // 判断标签页是否还有该页面
        if (state.tags.tagsList.map(v => v.name).includes(obj.name)) return
        state.tags.cachedViews.splice(obj.index, 1)
    },

    setRoutes(state: ILayout, data: Array<IMenubarList>): void {
        console.log(data)
        state.menubar.menuList = data
    },
    concatAllowRoutes(state: ILayout): void {
        allowRouter.reverse().forEach(v => state.menubar.menuList.unshift(v))
    },

    // 修改主题
    changeTheme(state: ILayout, num: number): void {
        if (num === state.setting.theme.mode) return
        if (typeof num !== 'number') num = state.setting.theme.mode
        changeTheme(num)
        state.setting.theme.mode = num
        // changeTheme(num)
        // localStorage.setItem('setting', JSON.stringify(state.setting))
    },
    changeTagsSetting(state: ILayout, multiPage: boolean): void {
        state.setting.multiPage = multiPage
        // localStorage.setItem('setting', JSON.stringify(state.setting))

        if (multiPage) {
            const index = state.tags.tagsList.findIndex(v => v.path === router.currentRoute.value.path)
            if (index !== -1) {
                state.tags.tagsList.forEach(v => v.isActive = false)
                state.tags.tagsList[index].isActive = true
            } else {
                mutations.changeTagNavList(state, router.currentRoute.value)
            }
        }
    },

    //更改导航布局  目前支持 侧边和顶部。后期追加混合布局
    changelayout(state: ILayout, type:string):void{
        state.setting.layout = type
        // localStorage.setItem('setting', JSON.stringify(state.setting))
    },
    changeThemeColor(state: ILayout, color:string):void{
        state.setting.theme.color = color
        changeTheme(state.setting.theme.mode)
        // localStorage.setItem('setting', JSON.stringify(state.setting))
    },
     SET_THEMECOLOR(state: ILayout, color:string):void{
        state.setting.theme.color = color
        changeTheme(state.setting.theme.mode)
    }

    
    
}
const actions = {

    async GenerateRoutes(): Promise<void> {
        // const res = await getRouterList()
        // const { Data } = res.data
        // const Data:Array<any> = [

        //     {
        //         id: 3,
        //         parentId: 0,
        //         name: 'Nav',
        //         path: '/Nav',
        //         component: 'Layout',
        //         redirect: '/Nav/SecondNav/ThirdNav',
        //         meta: { title: '多级导航', icon: 'el-icon-picture' }
        //     },
        //     {
        //         id: 30,
        //         parentId: 3,
        //         name: 'SecondNav',
        //         path: '/Nav/SecondNav',
        //         redirect: '/Nav/SecondNav/ThirdNav',
        //         component: 'SecondNav',
        //         meta: { title: '二级导航', icon: 'el-icon-camera', alwaysShow: true }
        //     },
        //     {
        //         id: 300,
        //         parentId: 30,
        //         name: 'ThirdNav',
        //         path: '/Nav/SecondNav/ThirdNav',
        //         component: 'ThirdNav',
        //         meta: { title: '三级导航', icon: 'el-icon-s-platform' }
        //     },
        //     {
        //         id: 31,
        //         parentId: 3,
        //         name: 'SecondText',
        //         path: '/Nav/SecondText',
        //         redirect: '/Nav/SecondText/ThirdText',
        //         component: 'SecondText',
        //         meta: { title: '二级文本', icon: 'el-icon-s-opportunity', alwaysShow: true }
        //     },
        //     {
        //         id: 310,
        //         parentId: 31,
        //         name: 'ThirdText',
        //         path: '/Nav/SecondText/ThirdText',
        //         component: 'ThirdText',
        //         meta: { title: '三级文本', icon: 'el-icon-menu' }
        //     },
        //     {
        //         id: 4,
        //         parentId: 0,
        //         name: 'Components',
        //         path: '/Components',
        //         component: 'Layout',
        //         redirect: '/Components/OpenWindowTest',
        //         meta: { title: '组件测试', icon: 'el-icon-phone' }
        //     },
        //     {
        //         id: 40,
        //         parentId: 4,
        //         name: 'OpenWindowTest',
        //         path: '/Components/OpenWindowTest',
        //         component: 'OpenWindowTest',
        //         meta: { title: '选择页', icon: 'el-icon-goods' }
        //     },
        //     {
        //         id: 41,
        //         parentId: 4,
        //         name: 'CardListTest',
        //         path: '/Components/CardListTest',
        //         component: 'CardListTest',
        //         meta: { title: '卡片列表', icon: 'el-icon-question' }
        //     },
        //     {
        //         id: 42,
        //         parentId: 4,
        //         name: 'TableSearchTest',
        //         path: '/Components/TableSearchTest',
        //         component: 'TableSearchTest',
        //         meta: { title: '表格搜索', icon: 'el-icon-question' }
        //     },
        //     {
        //         id: 43,
        //         parentId: 4,
        //         name: 'ListTest',
        //         path: '/Components/ListTest',
        //         component: 'ListTest',
        //         meta: { title: '标签页列表', icon: 'el-icon-question' }
        //     },
        //     {
        //         id: 5,
        //         parentId: 0,
        //         name: 'Permission',
        //         path: '/Permission',
        //         component: 'Layout',
        //         redirect: '/Permission/Directive',
        //         meta: { title: '权限管理', icon: 'el-icon-phone', alwaysShow: true }
        //     },
        //     {
        //         id: 50,
        //         parentId: 5,
        //         name: 'Directive',
        //         path: '/Permission/Directive',
        //         component: 'Directive',
        //         meta: { title: '指令管理', icon: 'el-icon-goods' }
        //     }
        // ]

        //将有权限的路由根据用户权限进行过滤 
        const arr = store.state.user.userInfo.permission
        const filterRoute: Array<IMenubarList> = []
        GenerateRouter.forEach(v => {
            arr.forEach((val: any) => {
                if (val.id === v.id) {
                    const obj = Object.assign({}, v)
                    obj.meta.permission = val.permission
                    filterRoute.push(obj)
                }
            })
        })
        generatorDynamicRouter(filterRoute)
    }
}
const layoutState = {
    namespaced: true,
    state,
    mutations,
    actions
}

export default layoutState
